package tech.bmatch.photo.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.bmatch.photo.model.Photo;
import tech.bmatch.photo.model.PhotoSeverInfo;
import tech.bmatch.photo.service.PhotoService;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class PhotoFileStoreServiceImpl implements PhotoService {

    /**
     * Logger
     */
    public static final Logger logger = LoggerFactory.getLogger(PhotoFileStoreServiceImpl.class);

    /**
     * Map映射
     */
    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 模拟图片数据库的json文件
     */
    private static File photosInfosFile = new File("./photos.json");

    /**
     * 存储所有图片的信息在内存中
     */
    private static Map<String, List<Photo>> photoCaches;

    /**
     * 储存图片服务器列表在内存中
     */
    private static List<PhotoSeverInfo> serverCaches;

    /**
     * 初始化读取所有图片的配Json文件到内存
     */
    static {

        //初始化图片信息
        photoCaches = new HashMap<>();
        try {
            initMapFromFile(objectMapper, photosInfosFile);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //初始化图片服务器列表
        if (serverCaches == null) {
            serverCaches = new ArrayList<>();
        }

        //以下为模拟服务器路径
        serverCaches.add(new PhotoSeverInfo(1, "./photoSever1"));
        serverCaches.add(new PhotoSeverInfo(2, "./photoSever2"));
        serverCaches.add(new PhotoSeverInfo(3, "./photoSever3"));
        serverCaches.add(new PhotoSeverInfo(4, "./photoSever4"));
        serverCaches.add(new PhotoSeverInfo(5, "./photoSever5"));
    }

    /**
     * 读取图片信息内容到Map中
     *
     * @param objectMapper
     * @param photosInfosFile
     */
    public static void initMapFromFile(ObjectMapper objectMapper, File photosInfosFile) {
        try {
            photoCaches = objectMapper.readValue(photosInfosFile, new TypeReference<Map<String, List<Photo>>>() {
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存Map到文件中
     */
    public static void store() {
        if (photoCaches == null) {
            return;
        }
        try {
            objectMapper.writeValue(photosInfosFile, photoCaches);
        } catch (IOException e) {
            logger.error("", e);
        }
    }


    /**
     * 获得图片Map
     *
     * @return
     */
    public Map<String, List<Photo>> getPhotosMap() {
        return photoCaches;
    }

    /**
     * 获得服务器列表List
     *
     * @return
     */
    public static List<PhotoSeverInfo> getServerCaches() {
        return serverCaches;
    }
}
